<script setup>
import { onMounted, ref } from 'vue';
import Task from '../../apis/Task';
import mapping from '../../utils/mapping.js';
import columns from '../../utils/Checkcolunms.js';
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus';
import refuse from '../../utils/refuseTask.js';

const taskCategoryMap = mapping;
const tableData = ref([]); // 数据
const totalItems = ref(0); // 总条目数
const itemsPerPage = ref(10); // 每页条目数
const currentPage = ref(1); // 当前页数

// 格式化数据
const formTaskData = (data) => {
  return data.map((item) => ({
    ...item,
    taskCategory: taskCategoryMap[item.taskCategory] || '未知类别', // 确保任务类别映射是有效的
  }));
};

// 获取数据
const fetchData = async () => {
  let typeIf = 'warning';
  try {
    const response = await Task.getTaskCheck({
      currentPage: currentPage.value,
      pageSize: itemsPerPage.value,
    });
    // console.log('后端返回的完整响应:', response); // 打印完整的响应
    // console.log('返回的数据:', response.data); // 打印数据部分

    if (response && response.data) {
      tableData.value = formTaskData(response.data); // 格式化数据
      totalItems.value = response.total; // 设置总条目数
    } else if (response.data === null) {
      typeIf = 'info';
      throw new Error('无多余的数据，请重新刷新');
    } else {
      throw new Error();
    }
  } catch (error) {
    ElNotification({
      title: '错误',
      message: error.message || '加载数据失败',
      type: typeIf,
    });
  }
};

onMounted(() => {
  fetchData();
});

// 分页变化
const handlePageChange = (page) => {
  currentPage.value = page; // 更新当前页
  fetchData(); // 获取新数据
};

// 每页条目数变化
const handlePageSizeChange = (size) => {
  itemsPerPage.value = size; // 更新每页条目数
  currentPage.value = 1; // 每页条目数变化时从第一页开始
  fetchData(); // 获取新数据
};

// 点击同意
const handleClick = async (taskId) => {
  try {
    // 弹出确认框
    await ElMessageBox.confirm('请仔细确认你的操作', 'Warning', {
      confirmButtonText: '确认',
      cancelButtonText: '撤回',
      type: 'warning',
    });
    const option = { taskId: taskId };
    const response = await Task.passTask(option);

    ElMessage({
      type: 'success',
      message: '审核通过',
    });
    await fetchData(); // 刷新数据
  } catch (error) {
    if (error === 'cancel') {
      // 判断是否是撤回操作
      ElMessage({
        type: 'info',
        message: '已撤回',
      });
    } else {
      // 其他错误
      ElNotification({
        title: '错误',
        message: error.message || '操作失败',
        type: 'error',
      });
    }
  }
};
//点击退返
const form = ref({
  taskId:'',
  requesterId: '',
  requesterName: '',
  objection: '',
});
//隐藏变量
const dialogFormVisible = ref(false);
const handleClickRefuse = async (data) => {
  try {
    //显示
    dialogFormVisible.value = true;
    //呈现 赋值
    form.value.requesterId = data.requesterId;
    form.value.requesterName = data.requesterName;
    form.value.taskId = data.taskId;
    console.log(form.value);
  } catch (error) {
    ElNotification({
      title: '错误',
      message: error.message || '操作失败',
      type: 'error',
    });
  }
};
//提交
const Oneobjection = ref();
const Twoobjection = ref();
const handleConfirmRefuse = async () => {
  try {
    form.value.objection = Oneobjection.value + Twoobjection.value;
    // 发起拒绝请求
    const response = await Task.refuseTask(form.value);
    ElMessage({
      type: 'success',
      message: '退返成功',
    });
    await  fetchData(); // 刷新数据
    // 请求成功后关闭弹窗
    dialogFormVisible.value = false;
  } catch (error) {
    ElNotification({
      title: '错误',
      message: error.message || '操作失败',
      type: 'error',
    });
  }
};
</script>

<template>
  <div>
    <el-card>
      <el-table :data="tableData" style="width: 100%" border="true">
        <el-table-column
          v-for="(column, index) in columns"
          :key="index"
          :label="column.label"
          :prop="column.props"
          :min-width="column.minWidth || 120"
          :fixed="column.fixed ? column.fixed : null"
        />
        <el-table-column fixed="right" label="审核" min-width="120">
          <template v-slot="scope">
            <el-button
              type="primary"
              size="small"
              @click="handleClick(scope.row.taskId)"
            >
              同意
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleClickRefuse(scope.row)"
              >退返</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <!-- 渲染分页组件 -->
        <el-pagination
          :total="totalItems"
          :page-size="itemsPerPage"
          :current-page="currentPage"
          @current-change="handlePageChange"
          @size-change="handlePageSizeChange"
          layout="total, prev, pager, next, sizes"
          :page-sizes="[10, 20, 30, 50]"
        />
      </div>
    </el-card>
  </div>
  <div>
    <el-dialog v-model="dialogFormVisible" title="退返理由书" width="500">
      <el-form :model="form">
        <el-form-item label="请求人身份号码" :label-width="formLabelWidth">
          <el-input
            :value="form.requesterId"
            readonly
            autocomplete="off"
            :placeholder="form.requesterId ? form.requesterId : 'E000000000000'"
          />
        </el-form-item>
        <el-form-item label="姓名" :label-width="formLabelWidth">
          <el-input
            :value="form.requesterName"
            readonly
            autocomplete="off"
            :placeholder="form.requesterName ? form.requesterName : '张三'"
          />
        </el-form-item>
        <el-form-item label="退返理由类别" :label-width="formLabelWidth">
          <el-select v-model="Oneobjection" placeholder="退返理由类别">
            <el-option
              v-for="(value, index) in refuse"
              :key="index"
              :label="value.label"
              :value="value.props"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="详细理由" :label-width="formLabelWidth">
          <el-input
            type="textarea"
            v-model="Twoobjection"
            autocomplete="off"
            placeholder="可是输入详细理由"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">撤回</el-button>
          <el-button type="primary" @click="handleConfirmRefuse">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="less"></style>
